package com.hrs.util;

import com.hrs.enity.ro.LoginResponseRo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.UUID;

/**
 * @author 摆渡人
 * @description
 * @date 2022/12/6 10:33
 */
@Slf4j
public class TokenUtil {
    /**
     * 过期时间
     */
    private static final int EXPIRE_SECONDS = 30 * 24 * 3600;
    /**
     * jwt加密字段
     */
    private static final String CLAIM_ID_KEY = "id";
    private static final String CLAIM_TYPE_KEY = "type";

    private static final String jwtKey = "human_resource_system";

    /**
     * 功能描述: 生成JWT TOKEN
     *
     * @param loginResponseRo
     * @return
     * @auther yandanyang
     * @date 2018/9/12 0012 上午 10:08
     */
    public static String generateToken(LoginResponseRo loginResponseRo) {
        Long id = loginResponseRo.getId();
        /**将token设置为jwt格式*/
        String baseToken = UUID.randomUUID().toString();
        LocalDateTime localDateTimeNow = LocalDateTime.now();
        LocalDateTime localDateTimeExpire = localDateTimeNow.plusSeconds(EXPIRE_SECONDS);
        Date from = Date.from(localDateTimeNow.atZone(ZoneId.systemDefault()).toInstant());
        Date expire = Date.from(localDateTimeExpire.atZone(ZoneId.systemDefault()).toInstant());

        Claims jwtClaims = Jwts.claims().setSubject(baseToken);
        jwtClaims.put(CLAIM_ID_KEY, id);

        return Jwts.builder().setClaims(jwtClaims).setNotBefore(from).setExpiration(expire).signWith(SignatureAlgorithm.HS512, jwtKey).compact();
    }

    /**
     * 功能描述: 根据登陆token获取登陆信息
     *
     * @param
     * @return
     * @auther yandanyang
     * @date 2018/9/12 0012 上午 10:11
     */
    public static Long getUidByToken(String token){
        Long uid = -1L;
        try {
            Claims claims = Jwts.parser().setSigningKey(jwtKey).parseClaimsJws(token).getBody();
            String idStr = claims.get(CLAIM_ID_KEY).toString();
            uid = Long.valueOf(idStr);
        } catch (Exception e) {
            return null;
        }
        return uid;
    }
}
